//
//  SwitchView.m
//  LogisticsProduct
//
//  Created by 孟学浩 on 2017/2/17.
//  Copyright © 2017年 com.puyiwang.logistics. All rights reserved.
//

#import "SwitchView.h"

#define BASE_TAG 200

@interface SwitchView()

@property (nonatomic,strong) UIView *lineView;          //线
@property (nonatomic,strong) UIButton *preSelectBtn;    //前一个选中按钮

@end

@implementation SwitchView

- (instancetype)initWithFrame:(CGRect)frame itemTitles:(NSArray *)itemTitles{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        CGFloat width = frame.size.width/itemTitles.count;
        for ( int i = 0; i<itemTitles.count; i++) {
            UIButton *button = [UIButton new];
            button.frame = CGRectMake(i*width, 0, width, self.frame.size.height);
            [button setTitle:itemTitles[i] forState:UIControlStateNormal];
            [button setTitleColor:getColor(@"333333") forState:UIControlStateNormal];
            button.titleLabel.font = DEF_FontSize_13;
            [button addTarget:self action:@selector(upInsideEvent:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = BASE_TAG+i;
            [self addSubview:button];
        }
        
        UIButton *firstBtn = [self viewWithTag:BASE_TAG];
        _preSelectBtn = firstBtn;
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 3, 50/WIDTH_5S_SCALE, 3)];
        _lineView.backgroundColor = getColor(mainColor);
        _lineView.center = CGPointMake(firstBtn.center.x, _lineView.center.y);
        [self addSubview:_lineView];
    }
    return self;
}

- (void)upInsideEvent:(UIButton *)sender{
    if (_preSelectBtn != sender) {
        [UIView animateWithDuration:.15 animations:^{
            _lineView.center = CGPointMake(sender.center.x, _lineView.center.y);
        }];
        [_preSelectBtn setTitleColor:getColor(@"333333") forState:UIControlStateNormal];
        [sender setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
        _preSelectBtn = sender;
        
        if (self.selectHandle) {
            self.selectHandle(sender.tag - BASE_TAG);
        }
    }
}

@end
